import Vue from 'vue'
import VueRouter from 'vue-router'
import A from '@/components/A.vue'
import AA from '@/components/AA.vue'
import B from '../components/B.vue'
import BB from '@/components/BB.vue'
import Login from '../components/Login.vue'
import Welcome from '../components/Welcome.vue'
import Dept from '@/components/Dept.vue'
import Emp from '@/components/Emp.vue'

Vue.use(VueRouter)

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    redirect: "/login",
  },
  {
    path: '/a/:id/:name',
    name: 'a',
    component: A,
    children: [{
      path: '/aa',
      component: AA,
    }]
  },
  {
    path: '/b',
    component: B,
    children: [{
      path: 'bb',
      component: BB,
    }]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/welcome',
    component: Welcome,
    //一级路由时默认自动跳转指定的二级路由页面
    redirect: '/welcome/emp',
    children: [
      {
        path: 'emp',
        component: Emp,
      },
      {
        path: 'dept',
        component: Dept,
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

//路由守卫应该写到const router 后面
// to: Route: 即将要进入的目标 路由对象
// from: Route: 当前导航正要离开的路由
// next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  const store = window.sessionStorage.getItem('storeData')
  console.log(store)
  if (store == null) {
    return next('/login')
  }
  next();
})

export default router
